package edu.ustb.services.weatherforecast.config;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Component;

@Aspect
@Component
public class ServiceLogAspect {

	private final static Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

	/**
	 * 定义拦截规则：拦截org.springframework.cloud.netflix.eureka.server包下面的所有类中
	 * 带有 @RequestMapping 注解的方法
	 */
	@Pointcut("execution(* org.springframework.cloud.netflix.eureka.serviceregistry.EurekaServiceRegistry.register(..))")
	public void controllerRequestPointcut() {}

	@Pointcut("execution(* edu.ustb.services.weatherforecast.controller.WeatherForecastController.queryWeather(..))")
	public void offerPointcut() {}

	@Around("controllerRequestPointcut()")
	public Object Interceptor(ProceedingJoinPoint pjp) {
		long totalTimingStart = System.currentTimeMillis();
		MethodSignature signature = (MethodSignature) pjp.getSignature();
		Method method = signature.getMethod();	// 获取被拦截的方法对象
		String methodName = method.getName();	// 方法名
		logger.warn("Commit请求开始。");
		Object result = null;

		try {
			if (result == null) {
				result = pjp.proceed();
			}
		} catch (Throwable e) {
			logger.error("exception: ", e);
			result = "发生异常：" + e.getMessage();
		}

		long totalCost = System.currentTimeMillis() - totalTimingStart;
		logger.warn("服务发布结束，总耗时：{}ms", totalCost);
		return result;
	}

	@Around("offerPointcut()")
	public Object offerInterceptor(ProceedingJoinPoint pjp) {
		Object result = null;
		try {
			if (result == null) {
				result = pjp.proceed();
			}
		} catch (Throwable e) {
			logger.error("Exception: ", e);
			result = "发生异常：" + e.getMessage();
		}

		return result;
	}
}
